package leetcode.t1Array;


/**
 * 27. 移除元素
 * 标记整理，类似java虚拟机标记整理算法，
 * @author K
 * @date 2024/1/17 13:41
 */
public class T27_RemoveElement {

    public static int removeElement(int[] nums, int val) {
        if (nums.length == 0) return 0;
        int count = 0;
        int lastIndex  = nums.length-1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                count++;
                while (lastIndex > i) {
                    if (nums[lastIndex] != val) {
                        nums[i] = nums[lastIndex];
                        nums[lastIndex] = 0;
                        lastIndex--;
                        break;
                    } else {
                        nums[lastIndex] = 0;
                    }
                    lastIndex--;
                }
            }
        }

        return nums.length - count;
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{3, 2, 2, 3};
        int result1 = removeElement(nums1, 3);
        int[] nums2 = new int[]{0, 1, 2, 2, 3, 0, 4, 2};
        int result2 = removeElement(nums2, 2);

        System.out.println();
    }

}
